package com.googlecode.continuity.core.server.mvc.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.acegisecurity.context.SecurityContextHolder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import com.googlecode.continuity.core.server.mvc.ContinuityModel;
import com.googlecode.continuity.core.server.mvc.command.EditUserCommand;
import com.googlecode.continuity.core.server.security.SecurityUserToken;

/**
 * AccountFormController manages the user account form, updating changed values in the database and serving information.
 *
 * @author Peter Schmitt <aragos@aragos.de>
 */
public class AccountFormController extends EditUserFormController {
  /**
   * Writed changed user account data to the database.
   *
   * @param obj submitted command object
   * @return success form model and view
   * @throws ServletException
   */
  public ModelAndView onSubmit(Object obj) throws ServletException {
    EditUserCommand command = (EditUserCommand) obj;
    SecurityUserToken userToken =
        ((SecurityUserToken) SecurityContextHolder.getContext().getAuthentication().getPrincipal());
    if (command.getNewpass1() != null) {
      userToken.setPassword(getUserService().encodePassword(command.getNewpass1()));
    }
    userToken.setUser(command.getUser());
    getUserService().storeUser(userToken);
    ContinuityModel model = new ContinuityModel();
    // TODO: make messaging formal, i.e. implement in model with lists and types. USE errors
    //model.put("successMessage", "Profile updated");
    logger.info("Returning account view after successfull update.");
    return new ModelAndView(new RedirectView(getSuccessView()), model);
  }

  /**
   * Creates a new {@link com.googlecode.continuity.core.server.mvc.command.EditUserCommand} populated with the
   * currently logged in user.
   *
   * @param request http request
   * @return new {@link com.googlecode.continuity.core.server.mvc.command.EditUserCommand}
   * @throws ServletException
   */
  protected Object formBackingObject(HttpServletRequest request) throws ServletException {
    return new EditUserCommand(
        ((SecurityUserToken) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUser());
  }
}
